package com.yanghx.user.server.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yangHX
 * createTime  2019/9/14 21:16
 */
public class CookieUtil {

    /**
     * 往cookie中设置值
     *
     * @param response response
     * @param name     name
     * @param value    value
     * @param expire   有效时常
     */
    public static void set(HttpServletResponse response, String name, String value, Integer expire) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        response.addCookie(cookie);
    }

    public static Cookie get(HttpServletRequest request,
                             String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie: cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }

        return null;
    }
}
